﻿using System.IO;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Serialization;
using System.Collections.Specialized;
using System.Web;

namespace RSuite.Services
{
    public abstract class WebServiceBase : IWebService
    {
        public Stream InvokeMethod(Stream data)
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

            var parameters = HttpUtility.ParseQueryString(new StreamReader(data).ReadToEnd());

            return this.WriteJson(this.Process(parameters["method"], this.FromJSON(parameters["parameters"])));
        }

        protected abstract object Process(string method, dynamic parameters);

        private Stream WriteJson(object value)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(this.ToJSON(value)));
        }

        protected string ToJSON(object value)
        {
            return new JavaScriptSerializer().Serialize(value);
        }

        protected object FromJSON(string json)
        {
            return new JavaScriptSerializer().Deserialize<dynamic>(json);
        }
    }
}